from django.shortcuts import render
from django.views.generic.base import View
# Create your views here.
from django.http.response import HttpResponse, JsonResponse
from .forms import ProductForm
from .models import Product, ProductInstance
from django.http.request import HttpRequest
from django.utils.decorators import method_decorator
from django.core.files.storage import FileSystemStorage
from jmbase.views import JMJsonBaseView

from django.conf import settings
import os

location = os.path.join(os.path.join(settings.MEDIA_ROOT, 'product'), 'richtext')
base_url = settings.MEDIA_URL + 'product/richtext/'


class UploadView(View):
    def post(self, request:HttpRequest):
        on_success = {
            "error": 0,
            "url": "http://www.example.com/path/to/file.ext"
        }

        on_failure = {
            "error": 1,
            "message": "错误信息"
        }

        img = request.FILES.get('imgFile')

        if img:
            fs = FileSystemStorage(location=location, base_url=base_url)
            name = fs.save(name=img.name, content=img)
            url_ = fs.url(name)
            on_success['url'] = url_
            return JsonResponse(on_success)

        return JsonResponse(on_failure)

    def get(self, request:HttpRequest):
        return HttpResponse('heep')

class ProductCateList(JMJsonBaseView):
    def get(self, request, data):
        pcs = Product.objects.all()
        result = {
            'list':[
                {
                    'name': pc.name,
                    'id': pc.id
                }
                for pc in pcs
            ]
        }

        return result

class ProductList(JMJsonBaseView):

    def get(self, request, data, pcid):

        ps = ProductInstance.objects.filter(product=pcid).values('name', 'main_img')

        result = {
            'list': [
                {
                    'name': p.get('name'),
                    'img': p.get('main_img')
                } for p in ps
            ]
        }

        return result


